var config = require('../config.js');

const Request = (url, method, data = {}) => {
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        url = config.HTTP_BASE_URL + url;
    }

    let realData = {};
    for (let key in data) {
        if (data[key] !== undefined) {
            realData[key] = data[key];
        }
    }
    console.log('args', url, method, realData, data);

    wx.showNavigationBarLoading()
    //data.method = method
    return new Promise((resove, reject) => {
        wx.request({
            url: url,
            data: realData,
            header: {},
            method: method.toUpperCase(), // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: function(res) {
                wx.hideNavigationBarLoading()
                if (res.statusCode == 200) {
                    resove(res.data)
                } else {
                    reject('fail')
                }
            },
            fail: function(msg) {
                console.log('request error', msg)
                wx.hideNavigationBarLoading()
                reject('fail')
            }
        })
    })
}

function Get(url, data = {}) {
    return Request(url, 'GET', data);
};

function Post(url, data = {}) {
    return Request(url, 'POST', data);
};

function Upload(url, file, data = {}) {
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        url = config.HTTP_BASE_URL + url;
    }
    wx.showNavigationBarLoading()
    data.method = method
    return new Promise((resove, reject) => {
        wx.uploadFile({
            url: url,
            filePath: file,
            name: "file",
            formData: data,
            success: (res) => {
                wx.hideNavigationBarLoading()
                resove(res.data)
            },
            fail: (err) => {
                console.log('reqest error', err)
                wx.hideNavigationBarLoading()
                reject('fail')
            }
        });
    })
};


module.exports = {
    get: Get,
    request: Request,
    post: Post,
    upload: Upload
};